<template>
  <div class='clazz_list'>
    <!-- <div class="page_info">
      <div class="title">注意：</div>
      <p>1. 添加班级前要先选中某个方向，表示将新班级添加到该方向下</p>
      <p>2. 组班之前要先选中某个班级</p>
    </div> -->
    <el-row>
      <!-- 左侧 -->
      <el-col :span="4">
       <div class="direction_clazz">
          <div class="title" style="text-align:center;background:#f2f2f8;padding:.5em 1em;border-radiux:5px;margin-bottom:.5em">方向班级</div>
          <el-tree accordion :data="directions" :props="{ children: 'clazzes', label: 'name' }" @node-click="handleNodeClick"></el-tree>
       </div>
      </el-col>
      <!-- /左侧 -->
      <!-- 右侧 -->
      <el-col :span="20">
        <div class="clazz_student">
          <!-- 按钮 -->
          <div class="btns">
            <el-row>
              <el-col :span="14">
                <el-form size="small" :inline='true'>
                  <el-form-item>
                    <el-cascader filterable v-model="param.channelIds" clearable :options="channels" placeholder="请选择渠道" :props="{ checkStrictly: true ,children:'children',label:'name',value:'id', emitPath: false,multiple:true}" ></el-cascader>
                  </el-form-item>
                  <el-form-item>
                    <el-input v-model="param.realname" style="width:100px" placeholder="姓名"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button  size="small" @click="loadStudents">搜索</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="10">
                <div style="text-align:right">
                  <el-button type="text" size="small" @click="toAddClazzHandler">添加班级</el-button>
                  <el-button type="primary" size="small" @click="toBatchChangeClazz">批量调班</el-button>
                  <el-button type="primary" size="small" @click="toSelectStudentHandler">组班</el-button>
                  <el-button type="primary" size="small" @click="toImportHandler">导入</el-button>
                  <el-button type="primary" size="small" @click="downloadHandler">导出</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
          <!-- 按钮结束 -->
          <!-- 学生数据 -->
          <!-- 表格 -->
          <div v-if="studentData.list == 0">
            <div style="text-align:center;padding :2em 0;color:red;font-size:12px">
              <div v-if="param.clazzId"> 该班级中还不存在学生，请尽快完成组班 </div>
              <div v-else> 您还未选中班级 </div>
            </div>
          </div>
          <div v-else>
            <el-table ref="multipleTable" :data="studentData.list" size="small" v-loading="loading"  
            :row-class-name="attentionStudentClass"
            @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" fixed="left"> </el-table-column>
              <el-table-column prop="realname" label="姓名" width="120" align="center" fixed="left"/>
              <!-- <el-table-column prop="stuNo" label="学号" width="100" align="center" /> -->
              <el-table-column prop="stuType" label="报名方式" width="120" align="center"/>
              <el-table-column label="报名时间" width="120" align="center">
                <template slot-scope="scope">
                  {{scope.row.applyTime | fmtDate}}
                </template>
              </el-table-column>
              <el-table-column prop="isAttention" label="是否关注" width="120" align="center">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.isAttention" type="primary" size="small">{{scope.row.isAttention}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="idCard" label="身份证号" width="180" align="center"/>
              <el-table-column prop="gender" label="性别" width="80" align="center"/>
              <el-table-column label="出生日期" width="120" align="center">
                <template slot-scope="scope">
                  {{scope.row.birth | fmtDate}}
                </template>
              </el-table-column>
              <el-table-column prop="homeAddress" label="家庭住址" width="300" align="center"/>
              <el-table-column prop="education" label="学历" width="120" align="center"/>
              <el-table-column prop="flp" label="外语水平" width="80" align="center"/>
              <el-table-column prop="tel" label="手机号" width="120" align="center"/>
              <el-table-column prop="guardianTel" label="监护人手机号" width="120" align="center"/>
              <el-table-column prop="qq" label="qq号" width="120" align="center"/>
              <el-table-column label="操作" align="center" width="80" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click.prevent="toChangeClazz(scope.row)">调班</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- /学生数据 -->
            <!-- 分页 -->
            <div class="page">
                <el-pagination background 
                  layout="prev, pager, next,sizes" 
                  small
                  :total="studentData.total" 
                  :page-size="studentData.pageSize" 
                  :current-page="studentData.page"
                  :page-sizes="[10, 15, 20,30,50]"
                  @size-change="handleSizeChange"
                  @current-change="currentChangeHandler">
                </el-pagination>
            </div>
            <!-- /分页 -->
          </div>
        </div>
      </el-col>
    </el-row>
     <!-- 导入学生抽屉 -->
    <Briupdrawer :drawer-visible="visible_import" title="导入学生信息" width="50%" @on-change-visible="handlerImportVisibleChange" >
      <div slot="content">
        <div class="sub_title"><strong>班级：</strong>{{param.clazzName}}</div>
        <p>1. 下载报名表模板</p>
        <div>
          <el-button type="primary" round size="small" @click="downloadTemplate">点击下载</el-button>
        </div>
        <p>2. 上传学生档案信息</p>
        <div style="text-align:center">
          <el-upload
            ref="upload"
            :auto-upload="false"
            class="upload-demo"
            :on-success="successSubmitHandler"
            drag
            :action='baseURL+"/student/uploadClazzStudent?clazzId="+param.clazzId'
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip" style="text-align:left;color:red;font-size:12px">
              <p >注意：</p>
              <strong>在导入数据前务必核对数据格式是否正确</strong>
              <p>系统会自动根据您填写的学校、学院设置该生渠道，如果该渠道在系统中不存在，则无法插入 </p>
            </div>
          </el-upload>
        </div>
        <div style="text-align:right">
          <el-button size="small" @click="visible_import = false">取消</el-button>
          <el-button size="small" type="primary" @click="importSubmitHandler">确定</el-button>
        </div>
      </div>
    </Briupdrawer>
    <!-- 导入学生抽屉 -->

    <!-- 抽屉 -->
    <Briupdrawer :drawer-visible="visible" :title="title" width="40%" @on-change-visible="handlerVisibleChange" >
      <div slot="content">
        <div class="sub_title">待选学生</div>
          <div style="padding-bottom:1em">
            <el-form size="small" inline>
              <el-form-item>
                <el-cascader filterable v-model="param_all.channelIds" clearable :options="channels" placeholder="请选择渠道"
            :props="{ checkStrictly: true ,children:'children',label:'name',value:'id', emitPath: false,multiple:true}" ></el-cascader>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="loadAllStudents">搜索</el-button>
              </el-form-item>
            </el-form>
          
          <el-checkbox-group v-model="checkList">
            <el-row>
              <el-col :span="4" v-for="s in allStudentData.list" :key="s.id">
                 <el-checkbox :label="s" >{{s.realname}}</el-checkbox>
              </el-col>
            </el-row>
          </el-checkbox-group>
        </div>
        <div class="sub_title">已选学生</div>
        <el-form ref="confirm_form" :model="form" :rules="rules" size="mini" label-position="center">
          <el-form-item prop="directionId">
            <el-checkbox-group v-model="checkList">
              <el-row>
                <el-col :span="4" v-for="s in checkList" :key="s.id">
                  <el-checkbox :label="s" >{{s.realname}}</el-checkbox>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="submitHandler">确 定</el-button>
      </span>
    </Briupdrawer>
    <!-- /抽屉 -->

    <!-- 班级抽屉 -->
    <Briupdrawer :drawer-visible="visible_clazz" :title="title_clazz" width="40%" @on-change-visible="handlerClazzVisibleChange" >
      <div slot="content">
        <el-form :model="form_clazz" ref="clazzForm" :rules="rules_clazz" label-width="80px" size="mini">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form_clazz.name"></el-input>
          </el-form-item>
          <el-form-item label="方向" prop="directionId" v-if="direction">
            {{direction.name}}
          </el-form-item>
          <el-form-item label="年度" prop="year">
            <el-select v-model="form_clazz.year">
              <el-option label="2020" value="2020"></el-option>
              <el-option label="2021" value="2021"></el-option>
              <el-option label="2022" value="2022"></el-option>
              <el-option label="2023" value="2023"></el-option>
              <el-option label="2024" value="2024"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="介绍" prop="introduce">
            <el-input type="textarea" v-model="form_clazz.introduce"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible_clazz = false">取 消</el-button>
        <el-button type="primary" size="small" @click="submitClazzFormHandler">确 定</el-button>
      </span>
    </Briupdrawer>
    <!-- 班级抽屉 -->

    <!-- 抽屉 -->
    <Briupdrawer :drawer-visible="visible_change_clazz" title="调整班级" width="55%" @on-change-visible="handlerVisibleChangeClazzChange" >
      <div slot="content">
          <div class="sub_title">学生信息</div>
          <el-table size="small" :data="students">
              <el-table-column type="index" :index="1" label="序号" align="center" fixed="left"/>
            <el-table-column prop="realname" label="姓名" width="90" align="center" fixed="left"/>
            <el-table-column prop="idCard" label="身份证号" align="center"/>
            <el-table-column prop="clazz" label="班级" align="center"/>
          </el-table>
          <div class="sub_title">调班信息</div>
          <el-form size="small" :model="form_clazz_change" label-width="100px" :rules="rules_change_clazz" ref="form_change_clazz">
            <el-form-item label="调整班级" prop="clazzId">
               <el-cascader filterable v-model="form_clazz_change.clazzId" clearable :options="directionClazzTree" placeholder="请选择班级" :props="{ children:'clazzes',label:'name',value:'id',emitPath: false}" ></el-cascader>
            </el-form-item>
            <el-form-item label="备注信息" prop="comment">
              <el-input type="textarea" v-model="form_clazz_change.comment" :rows="4"></el-input>
            </el-form-item>
          </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="submitStudentChangeClazzHandler">确 定</el-button>
      </span>
    </Briupdrawer>
    <!-- /抽屉 -->
  </div>
</template>

<script>
import {get,post,postJSON,download} from '@/utils/request'
import _ from 'lodash'
import qs from 'qs'
import { mapGetters } from 'vuex'
export default {
  // 组件名称
  name: 'demo',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data () {
    return {
      baseURL:process.env.VUE_APP_BASE_API,
      directions:[],
      param:{
        page:1,
        pageSize:15
      },
      param_all:{
        page:1,
        pageSize:100,
        status:'待分班'
      },
      studentData:{list:[]},
      allStudentData:{list:[]}, // 待选择
      checkList:[], // 已选择的学生
      title:'组班',
      visible:false,
      form:{},
      rules: {
        tel: [ { required: true, message: '请输入手机号', trigger: 'blur' } ]
      },
      // 班级
      direction:null,
      title_clazz:'',
      visible_clazz:false,
      form_clazz:{
        year:(new Date()).getFullYear()
      },
      rules_clazz:{
        name: [ { required: true, message: '请输入名称', trigger: 'blur' } ],
        introduce: [ { required: true, message: '请输入简介', trigger: 'blur' } ],
        year: [ { required: true, message: '请选择年度', trigger: 'change' } ],
      },
      rules_change_clazz:{
        clazzId: [ { required: true, message: '请选择班级', trigger: 'change' } ],
        comment: [ { required: true, message: '请输入备注信息', trigger: 'blur' } ]
      },
      form_clazz_change:{},
      visible_change_clazz:false,
      students:[],
      visible_import:false,
    }
  },
  // 计算属性
  computed: {
    ...mapGetters(['channels','directionClazzTree']),
  },
  // 组件方法
  methods: {
    importSubmitHandler() {
      this.$refs.upload.submit();
    },
    // 下载模板
    downloadTemplate(){
      download('/student/downloadClazzStudentTemplate');
    },
    // 导入成功
    successSubmitHandler(response){
      this.$message({ message: response.message, type: response.status === 200?'success':'error' })
      this.loadStudents();
      this.visible_import = false;
    },
    // 去导入
    toImportHandler(){
      if(this.param.clazzId){
        this.visible_import = true;
      } else {
        this.$message.success({message:"请先选中班级"})
      }
    },
     // 重点关注学生
    attentionStudentClass({row, rowIndex}){
      let flag = '';
      switch(row.isAttention){
        case '关系学生':
          flag = 'success-row'
          break;
        case '问题学生':
          flag = 'warning-row'
          break;
        default:
          flag = ''
      }
      return flag;
    },
    handlerVisibleChangeClazzChange(val){
      this.visible_change_clazz = val;
    },
     // 提交调班信息
    submitStudentChangeClazzHandler(){
      this.$refs['form_change_clazz'].validate((valid) => {
        if (valid) {
          let url = '/student/changeClazz'
          post(url,this.form_clazz_change).then(response => {
            this.$message({ message: response.message, type: 'success' })
            this.loadStudents()
            this.visible_change_clazz = false
          });
        } else {
          return false
        }
      })
    },
    // 去批量调班
    toBatchChangeClazz(){
      this.form_clazz_change.studentIds = this.students.map(item => item.id);
      this.visible_change_clazz = true;
    },
    // 调整班级
    toChangeClazz(student){
      this.$refs.multipleTable.clearSelection();
      this.students = [student]

      this.form_clazz_change.studentIds = this.students.map(item => item.id);
      this.visible_change_clazz = true;
    },
    
    // 去添加班级
    toAddClazzHandler(){
      if(!this.direction){
        this.$message({type:'warning',message:'请先选择一个方向'})
        return false;
      }
      this.title_clazz="新增班级信息"
      this.form_clazz = {
        year:(new Date()).getFullYear(),
        directionId :this.direction.id
      }
      this.visible_clazz = true;
    },
    // 保存班级
    submitClazzFormHandler(){
    // 表单校验
      this.$refs['clazzForm'].validate((valid) => {
        if (valid) {
          // 校验通过后，完成数据交互
          let url = '/clazz/saveOrUpdate'
          post(url,this.form_clazz).then(response => {
            this.$message({type:"success",message:response.message})
            this.loadDirections();
            this.visible_clazz = false;
          })
        } else {
          return false;
        }
      });
    },
    // 确认提交
    submitHandler(){
      let url = '/student/batchConfirmClazz'
      let ids = this.checkList.map(item => item.id);
      let data = {clazzId:this.param.clazzId,ids}
      postJSON(url,data).then(response => {
        this.$message({ message: response.message, type: 'success' })
        this.loadStudents();
        this.visible = false
      })
    },
    // 导出班级学生信息
    downloadHandler(){

    },
    // 去选人入班
    toSelectStudentHandler(){
      if(!this.param.clazzId){
        this.$message({message:'您还未选中班级',type:"error"})
        return false;
      }
      this.checkList = []
      this.loadAllStudents();
      this.visible = true;
    },
    // 处理点击节点事件
    handleNodeClick(node){
      if(!node.clazzes){
        this.param.clazzId = node.id;
        this.param.directionId = node.directionId;
        this.param.clazzName = node.name;
        this.loadStudents();
      } else {
        // 维护方向和班级
        delete this.param.clazzId;
        //this.param.directionId =node.id;
        // 维护方向
        this.direction = node;
        this.param_all.directionId =node.id;
        this.param = _.clone(this.param);
      }
    },
    // 加载方向及班级信息
    loadDirections(){
      let url = "/direction/queryDirectionClazzTree"
      get(url).then(response => {
        this.directions = response.data;
      })
    },
    // 加载学生信息
    loadStudents(){
      this.loading = true;
      let url = '/student/pageQuery'
      get(url+"?"+qs.stringify(this.param,{ arrayFormat: 'repeat' }))
      .then(response => {
        this.studentData = response.data
        this.loading = false;
      })
    },
    // 加载学生信息
    loadAllStudents(){
      let url = '/student/pageQuery'
      get(url+"?"+qs.stringify(this.param_all,{ arrayFormat: 'repeat' }))
      .then(response => {
        this.allStudentData = response.data
      })
    },
    // 当前页发生改变
    currentChangeHandler(page){
      this.param.page = page;
      this.loadStudents();
    },
     // 处理分页大小变化的函数
    handleSizeChange(pageSize){
      // 当前页为第一页
      this.page = 1;
      // 页面大小为用户选择的页面
      this.param.pageSize = pageSize;
      this.loadStudents();
    },
    //处理visible变化的钩子函数,解决抽屉无法收缩的bug
    handlerVisibleChange(val){
      this.visible = val;
    },
    handlerClazzVisibleChange(val){
      this.visible_clazz = val;
    },
    handleSelectionChange(val) {
      this.students = val;
    },
    handlerImportVisibleChange(val){
      this.visible_import = val;
    }
  },
  mounted () {
    // 加载方向
    this.loadDirections();
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style lang="scss" scoped>
.clazz_list {
  .direction_clazz {
    padding-right: 2px;
    min-height: 500px;
    border-right: 1px solid #efefef;
  }
  .clazz_student {
    padding:0 .5em ;
  }
}
</style>
